﻿using Furion;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BaseNet.Core.Utils
{
    /// <summary>
    /// npoi导出excel
    /// </summary>
    public class NpoiHelper
    {
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="headerList"></param>
        /// <param name="dataList"></param>
        /// <param name="fileName"></param>
        public static string ExportExcel<T>(List<string> headerList, List<T> dataList, string fileName)
        {
            //1.创建表格
            var workbook = new XSSFWorkbook();
            //2.创建第一页
            var sheet = workbook.CreateSheet("sheet1");
            //3.创建第一页标题列
            var firstRow = sheet.CreateRow(0);
            //4.遍历赋值标题列
            int columIndex = 0;
            foreach (var item in headerList)
            {
                sheet.SetColumnWidth(columIndex, 20 * 256);//设置列宽
                var cell = firstRow.CreateCell(columIndex);
                cell.SetCellValue(item);

                columIndex++;
            }
            //5.填充数据
            for (int i = 0; i < dataList.Count; i++)
            {
                var item = dataList[i];

                IRow row = sheet.CreateRow(i + 1);

                int index = 0;
                foreach (PropertyInfo p in typeof(T).GetProperties())//遍历入参循环赋值
                {
                    var cell = row.CreateCell(index);
                    var value = typeof(T).GetProperty(p.Name).GetValue(item);
                    if (value != null)
                    {
                        if (value.GetType() != typeof(List<string>))//若是字段为AttachedImgList，表示其为图片，插入图片
                        {
                            //实体类所对应的属性
                            cell.SetCellValue(value?.ToString());
                        }
                    }
                    index++;
                }
            }
            //6.保存
            var suffix = Path.GetExtension(fileName).ToLower().Replace(".", "");
            var rootRelativePath = "/uploads/" + suffix + "/" + DateTime.Now.ToString("yyyyMM");//制造一个相对路径
            var savePath = App.HostEnvironment.ContentRootPath + rootRelativePath;
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            using (FileStream fs = new FileStream(Path.Combine(savePath, fileName), FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);
            }
            //7.返回文件地址
            return Path.Combine(rootRelativePath, fileName);
        }
    }
}
